'use strict';
//点评
const Controller = require('egg').Controller;
class CommentController extends Controller {
    async index() {
        const {
            ctx,
            app
        } = this;
        const {
            id,
            openid, 
            username,
            product_name,
            page = 1,
            number = 5
        } = ctx.request.query;
        console.log(id);
        // 如果page=2,则offset = 2,翻页为第二页,这个page是根据后台传进来的
        const offset = (page - 1) * number
        let data, count; //data数据 ， count全部数据的数量
        if (username && page) {
            data = await app.mysql.query(`select * from comment where username like '%${username}%' limit ${offset},${number}`);
            count = await app.mysql.query(`select count(*) as count from comment where username like '%${username}%'`);
        } else if (product_name && page) {
            const names = await app.mysql.query(`select name from product`);
            const name11 = names.filter(item => item.name == product_name);
            if (name11.length != 0) {
                data = await app.mysql.query(`select * from comment where product_name like '${name11[0].name}' limit ${offset},${number}`);
                count = await app.mysql.query(`select count(*) as count from comment where product_name like '${name11[0].name}'`);
            }else{
                ctx.body = {
                    code: 4005,
                    msg: '查询失败，该手机目前还没有评论！',
                }
            }
        } else if (id && page) {
            data = await app.mysql.query(`select * from comment where pid like '${id}' limit ${offset},${number}`);
            count = await app.mysql.query(`select count(*) as count from comment where pid like '${id}'`);
        } else if( openid && page){
            data = await app.mysql.query(`select * from comment where openid like '${openid}' limit ${offset},${number}`);
            count = await app.mysql.query(`select count(*) as count from comment where openid like '${openid}'`);
        }else {
            data = await app.mysql.query(`select * from comment limit ${offset},${number}`);
            count = await app.mysql.query(`select count(*) as count from comment`);
        }
        if (count[0].count != 0) {
            ctx.body = {
                code: 0,
                msg: '查询成功',
                data,
                count: count[0].count,
            }
        } else {
            ctx.body = {
                code: 4004,
                msg: '查询失败，没有数据',
            }
        }
    }
    async pick() { //配合修改数据的使用
        const {
            ctx,
            app
        } = this;
        const {
            id
        } = ctx.params;
        const result = await app.mysql.get('adminuser', {
            ID: id
        })
        if (result) {
            ctx.body = {
                code: 0,
                msg: '查找成功',
                data: result
            };
        } else {
            ctx.body = {
                code: 4007,
                msg: "查找失败"
            }
        }
    }
    async create() { //新增
        const {
            ctx,
            app
        } = this;
        // 从web页面传过来的数据

        let {
            id,
            openid,
            username,
            product_name,
            content,
            Score,
            appearance,
            performance,
            price,
            ImgUrl,
            tupian,
            portrait
        } = ctx.request.body;
        console.log(1111111111555555);
        console.log(id);
        let star;
        //图片可以为空
        ImgUrl=ImgUrl.length===0?'':ImgUrl;
        // 数据不能缺少，否则不能新增成功
        
        if (id && openid && username && product_name && content && Score && appearance && performance && price && portrait ) {
            const result = await app.mysql.query(`select id,username,product_name from comment`);
            // 如果查找到的名字一样,则不能添加同名的管理员
            const result1 = result.filter(item => item.product_name == product_name && item.username == username);
            const time = Math.floor(Date.now()/1000);//直接用 new Date(时间戳) 格式转化获得当前时间
            // const times = time.toLocaleDateString().replace(/\//g, "-") + " " + time.toTimeString().substr(0, 8);//再利用拼接正则等手段转化为yyyy-MM-dd hh:mm:ss 格式
            // 不过这样转换在某些浏览器上会出现不理想的效果，因为toLocaleDateString()方法是因浏览器而异的，比如 IE为2016年8月24日 22:26:19 格式 搜狗为Wednesday, August 24, 2016 22:39:42
            if (result1.length != 0) {
                const dd = await app.mysql.query(`select id from comment where product_name like "%${product_name}%" and username like  "%${username}%" `);
                const options = {
                    // 将要修改的数据,放到获取的id那一列数据
                    where: {
                        id: +dd[0].id
                    }
                };
                console.log(11);
                console.log(time);
                const row = {
                    pid:id,
                    openid,
                    username,
                    product_name,
                    content,
                    Score,
                    appearance,
                    performance,
                    price,
                    ImgUrl: ImgUrl,
                    tupian,
                    portrait,
                    time: time
                }
                const result2 = await app.mysql.update('comment', row, options)
                if (result2) {
                    if(id){
                        const count = await app.mysql.query(`select COUNT(*) as count from comment where pid=${id}`);
                        const sum = await app.mysql.query(`select SUM(Score) as sum from comment where pid=${id}`);
                        // console.log(count[0].count,sum[0].sum);
                        star = sum[0].sum/count[0].count
                        console.log(star)
                        await app.mysql.query(`UPDATE product SET star=${star} WHERE id=${id}`)
                    }
                    ctx.body = {
                        code: 0,
                        msg: "评论修改成功",
                    }
                } else {
                    ctx.body = {
                        code: 4002,
                        msg: "评论修改失败",
                    }
                }
            } else {
                console.log(22);
                console.log(time)
                const row = {
                    pid:id,
                    openid,
                    username: username,
                    product_name: product_name,
                    content: content,
                    Score: Score,
                    appearance: appearance,
                    performance: performance,
                    price: price,
                    ImgUrl: ImgUrl,
                    tupian:tupian,
                    portrait: portrait,
                    time:time
                }
                // 插入数据库的 comment
                const data = await app.mysql.insert('comment', row);
                if(id){
                    const count = await app.mysql.query(`select COUNT(*) as count from comment where pid=${id}`);
                    const sum = await app.mysql.query(`select SUM(Score) as sum from comment where pid=${id}`);
                    // console.log(count[0].count,sum[0].sum);
                    star = sum[0].sum/count[0].count
                    console.log(star)
                    await app.mysql.query(`UPDATE product SET star=${star} WHERE id=${id}`)
                }
                ctx.body = {
                    code: 0,
                    msg: "评论成功",
                    data: row,
                };
            }

        } else {
            ctx.body = {
                code: 4005,
                msg: '缺少默认参数'
            }
        }
        
    }
    async update() { //修改
        const {
            ctx,
            app
        } = this;
        const {
            id
        } = ctx.params; //获取需要修改的数据id
        const {
            content,
            Score,
            appearance,
            performance,
            price,
            ImgUrl
        } = ctx.request.body;
        const row = {
            content: content,
            Score: Score,
            appearance: appearance,
            performance: performance,
            price: price,
            ImgUrl: ImgUrl,
            portrait: portrait
        }
        const options = {
            // 将要修改的数据,放到获取的id那一列数据
            where: {
                id: +id
            }
        };
        // console.log('修改456654543212');
        // console.log(username,
        //     product_name,
        //     content,
        //     Score,
        //     appearance,
        //     performance,
        //     price);
        if (row && options) {
            const result = await app.mysql.update('comment', row, options);
            if (result) {
                ctx.body = {
                    code: 0,
                    msg: "编辑成功",
                };
            } else {
                ctx.body = {
                    code: 4008,
                    msg: "编辑失败",
                };
            }
        } else {
            ctx.body = {
                code: 4009,
                msg: '缺少必要参数'
            }
        }
    }
    // 删除
    async destroy() {
        const {
            ctx,
            app
        } = this;
        const {
            id
        } = ctx.params;
        const result = await app.mysql.delete(`comment`, {
            id: +id
        })
        if (result) {
            ctx.body = {
                code: 0,
                msg: "删除成功",
            };
        } else {
            ctx.body = {
                code: 4007,
                msg: "删除失败",
            };
        }
    }

}
module.exports = CommentController;